import java.util.Enumeration;

import javax.media.j3d.Behavior;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.Bounds;
import javax.media.j3d.WakeupOnElapsedFrames;
import javax.vecmath.Point3d;

import tracker.TrackerThread;

import com.sun.j3d.utils.geometry.Text2D;

/*
 * class to handle computing the FPS the system is running at.
 */
public class FPSBehavior extends Behavior {

	/** the System.milliseconds since updating the FPS text */
	private long lastTick = 0;
	
	/** this behaviour must wakeup every frame */
	private WakeupOnElapsedFrames nextFrame = new WakeupOnElapsedFrames(0);
	
	/** the number of frames that have ellapsed since updating the FPS text */
	private int frameCount = 0;
	
	/** the text object for the graphics' FPS */
	private Text2D graphicsFPSText;
	
	/** the text object for the trackers' FPS */
	private Text2D trackerFPSText;
	
	/** tracker thread to determine the FPS of the tracker */
	private TrackerThread headTracker;
	
	/** the OverlayGroup containg the FPS text */
	private OverlayGroup overlay;
	
	/** is this the first time we've drawn a frame? */
	private boolean firstFrame = true;
	

	
	public FPSBehavior(Text2D graphicsFPSText, Text2D trackerFPSText, TrackerThread headTracker, OverlayGroup og){
		this.overlay = og;
		this.graphicsFPSText = graphicsFPSText;
		this.trackerFPSText = trackerFPSText;
		this.headTracker = headTracker;
		Bounds bound = new BoundingSphere(new Point3d(), Double.MAX_VALUE);
		this.setSchedulingBounds(bound);
	}
	
	public void initialize() {
		lastTick = System.currentTimeMillis();
		this.wakeupOn(nextFrame);
	}

	
	public void processStimulus(Enumeration arg0) {
		
		if (firstFrame){
    		overlay.updatePlacement();
    		firstFrame = false;
    	}
		
		frameCount++;
		long timePassed = System.currentTimeMillis() - lastTick;
		
		if (timePassed >= 1000){

			// display the FPS of the tracker 
			if (headTracker != null && trackerFPSText != null)
				if (!headTracker.getReaquiringTracker())
					this.trackerFPSText.setString("Polhemus FPS = " + headTracker.getFPS() + " / " + headTracker.getTracker().getMaxUpdateSpeedInHz() / headTracker.getTracker().getNumSensors());
				else
					this.trackerFPSText.setString("Tracker Lost Reset = " + headTracker.getRetryCount());
			
			/* update the fps */
			int fps = (int)(frameCount / (timePassed / 1000.0f));
			if(graphicsFPSText != null)
        		graphicsFPSText.setString("FPS = " + fps);
			frameCount = 0;
			lastTick = System.currentTimeMillis();
		}
		this.wakeupOn(nextFrame);
	}

}